package com.jiangyg.devtools.execute.beantojson;

import com.intellij.json.JsonLanguage;
import com.intellij.openapi.project.Project;
import com.intellij.ui.EditorTextField;
import com.jiangyg.devtools.ui.AbstractDialogWrapper;
import com.jiangyg.devtools.ui.EditorTextAreaBuilder;
import com.jiangyg.devtools.toolkit.JsonUtils;
import com.jiangyg.devtools.toolkit.AwtUtils;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;

import javax.swing.*;
import java.awt.event.ActionEvent;
import java.util.Objects;

/**
 * 类描述：
 *
 * @author jiangyg
 * @date 2023-08-17
 */
public class BeanToJsonDialogWrapper extends AbstractDialogWrapper {

    private final String text;

    private boolean formated = true;

    private final EditorTextField textArea;

    public BeanToJsonDialogWrapper(String text, @Nullable Project project) {
        super(project);

        this.text = text;
        this.textArea = EditorTextAreaBuilder.instance()
                .project(project).defaultFeatures().build(JsonLanguage.INSTANCE);

        init();

        this.setTitle("JSON");
        this.setSizeByRatio(0.4, 0.8);
    }

    @Override
    protected @Nullable JComponent createCenterPanel() {
        setJsonText();
        return textArea;
    }

    @Override
    protected Action @NotNull [] createActions() {
        this.setCancelButtonText("关闭");
        this.setOKButtonText("复制并关闭");
        return new Action[]{getCancelAction(), new FormateAction(), getOKAction()};
    }

    @Override
    protected void doOKAction() {
        AwtUtils.setClipboardContents(textArea.getText());

        super.doOKAction();
    }

    private String formateBtnText() {
        formated = !formated;
        return !formated ? "取消格式化" : "格式化";
    }

    private void setJsonText() {
        if (formated) {
            textArea.setText(JsonUtils.toPrettyString(text));
        } else {
            textArea.setText(text);
        }
    }

    protected final class FormateAction extends DialogWrapperAction {

        private FormateAction() {
            super(formateBtnText());
            putValue(FOCUSED_ACTION, Boolean.TRUE);
        }

        @Override
        protected void doAction(ActionEvent e) {
            setJsonText();

            Objects.requireNonNull(getButton(this)).setText(formateBtnText());
        }

    }

}
